package com.example.androidautoproject

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import com.example.androidautoproject.service.AndroidHttpServer
import com.example.androidautoproject.service.ScreenCaptureForegroundService
import com.example.androidautoproject.utils.AdParam
import com.example.androidautoproject.utils.OverlayStart
import com.ven.assists.AssistsCore
import java.io.IOException
import java.net.Inet4Address
import java.net.NetworkInterface

@Suppress("UNREACHABLE_CODE")
class MainActivity : ComponentActivity() {
    private val serverPort = 8088
    private lateinit var httpServer: AndroidHttpServer
    private val REQUEST_SCREENSHOT_PERMISSION = 1001
    private val TAG = "ServerProject"

    companion object{
        private const val REQUEST_CODE_MEDIA_PROJECTION = 100
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.btn_test).setOnClickListener{
            if(AssistsCore.isAccessibilityServiceEnabled()){
                OverlayStart.show()
            }else{
                AssistsCore.openAccessibilitySetting()
            }
        }

//        findViewById<Button>(R.id.btn_screen).setOnClickListener{
//            requestMediaProjectionPermission()
//        }

        // 创建并启动服务器
        httpServer = AndroidHttpServer(serverPort, this)
        try {
            httpServer.start()
            Log.d(TAG, "✅ Server STARTED at port $serverPort")
            Log.d(TAG, "📡 Local URL: http://127.0.0.1:$serverPort")
            Log.d(TAG, "🌐 Network URL: http://${getLocalIpAddress()}:$serverPort")
            var list = getLocalIpAddress()?.split('.')
            var size = list?.size
            if(size != null && size > 0 && list != null){
                var ip = list[size - 1]
                Log.e(TAG, ip)
                AdParam.ip = ip
            }
        } catch (e: IOException) {
            Log.e(TAG, "Error starting server: ${e.message}")
        }

        // 检查并请求权限
        checkPermissions()

        if (intent != null && intent.getBooleanExtra("REQUEST_MEDIA_PROJECTION", false)) {
            requestMediaProjectionPermission()
        }
    }

    private fun requestMediaProjectionPermission(){
        var mediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        var captureIntent = mediaProjectionManager.createScreenCaptureIntent()
        startActivityForResult(captureIntent, REQUEST_CODE_MEDIA_PROJECTION)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_MEDIA_PROJECTION -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    // 启动前台服务，传递 resultCode 和 data
                    val serviceIntent = Intent(this, ScreenCaptureForegroundService::class.java).apply {
                        action = "ACTION_START_CAPTURE" // 自定义 Action
                        putExtra("EXTRA_RESULT_CODE", resultCode)
                        putExtra("EXTRA_RESULT_DATA", data)
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startForegroundService(serviceIntent)
                    } else {
                        startService(serviceIntent)
                    }
                } else {
                    Toast.makeText(this, "Screen capture permission denied", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun checkPermissions() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
                requestPermissions(
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    REQUEST_SCREENSHOT_PERMISSION
                )
            }
        }
        // Android 13+ 需要额外权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
                    REQUEST_SCREENSHOT_PERMISSION
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_SCREENSHOT_PERMISSION) {
            if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                Toast.makeText(this, "Screenshot permissions granted", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "Screenshot permissions denied", Toast.LENGTH_LONG).show()
            }
        }
    }

    fun getLocalIpAddress(): String? {
        return try {
            val interfaces = NetworkInterface.getNetworkInterfaces().toList()
            interfaces
                .filter { it.isUp && !it.isLoopback }
                .flatMap { it.inetAddresses.toList() }
                .firstOrNull { addr ->
                    addr is Inet4Address && !addr.isLoopbackAddress && !addr.isLinkLocalAddress
                }?.hostAddress
        } catch (e: Exception) {
            Log.e(TAG, "Error getting IP: ${e.message}")
            null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止服务器
        httpServer.stop()
        Log.d(TAG, "Server stopped")
    }
}

